package com.example.saiaadmin.hander;

import com.example.saiaadmin.common.RedisUtils;
import com.example.saiaadmin.entry.EbSystemUser;
import com.example.saiaadmin.po.CusterUserDetails;
import com.example.saiaadmin.utils.ResultData;
import com.fasterxml.jackson.databind.ObjectMapper;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.logout.LogoutSuccessHandler;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.concurrent.TimeUnit;

/**
 * security退出成功
 */
@Component
public class LogoutAuthenticationSuccessHandler implements LogoutSuccessHandler {
    private static final Logger log = LoggerFactory.getLogger(LogoutAuthenticationSuccessHandler.class);
    @Autowired
    private RedisUtils redisUtils;
    @Override
    public void onLogoutSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        CusterUserDetails user = (CusterUserDetails) authentication.getPrincipal();
        if(null != user && null != user.getUser()){
            EbSystemUser systemUser = user.getUser();
            redisUtils.delete(systemUser.getUsername()+"Authorization");
        }

        String value = new ObjectMapper().writeValueAsString(ResultData.success("退出成功"));
        response.setStatus(200);
        // 设置响应内容类型为JSON
        response.setContentType("application/json");
        // 设置字符编码为UTF-8
        response.setCharacterEncoding("UTF-8");
        // 获取response的writer对象
        PrintWriter out = response.getWriter();
        out.write(value);
        log.info("退出成功");
        // 清空缓冲区，发送数据
        out.flush();
        out.close();

    }
}
